import React, {
    useState,
    useLayoutEffect,
    useEffect
} from "react";
import Modal from "../modal";
import { message, Popover } from "antd";
import Scrollbars from "react-custom-scrollbars";
import GroupOne from "./groupOne";
import fetch from "@/util/fetch";
import "./index.scss";
/**
 * 使用该组件时需要在sessionStorage里存储几个公共信息，schoolType, schoolId
 * 
 * visible 控制显隐的变量
 * width 弹窗宽度
 * height 弹窗高度
 * title 弹窗标题
 * changeVisible  控制显隐的函数
 * originList  传入已选择的用户列表数组
 * getList  获取选择的用户列表函数【每个对象必须包含groupType】
 * 
 */

/**
 * type: user(用户), grade(年级), class(班级), group(教师/教研组), identity(管理员身份), org(部门)
 * groupType: admin(管理员), tea(教师), stu(学生), parent(家长), org(部门)
 * 
 */
const groupTypeInfo = {
    "admin": "管理员",
    "tea": "教师",
    "stu": "学生",
    "parent": "家长",
    "org": "部门"
}
function SelectModal(props){
    let {
        visible,
        width,
        height,
        title,
        changeVisible,
        originList,
        getList
    } = props;

    width = width? width: 900;
    height = height? height: 592;

    const [selectList, setSelectList] = useState([]);
    const [searchList, setSearchList] = useState([]);
    const [keyword, setKeyword] = useState("");
    const [searchVisible, setSearchVisible] = useState(false);
    const [groupList, setGroupList] = useState([
        {
            name: "全部管理员",
            id: "admin"
        },
        {
            name: "全部老师",
            id: "tea"
        },
        {
            name: "全部学生",
            id: "stu"
        },
        {
            name: "全部家长",
            id: "parent"
        },
        {
            name: "学校组织结构",
            id: "org"
        },
    ]);
    //搜索用户
    const searchUserMethod = () => {
        if(!keyword){
            return;
        }
        let url = window.BasicProxy + "/api/commons/school/user/search";
        fetch
        .get({url, params: {
            schoolId: sessionStorage.getItem("schoolId"),
            keyword: keyword
        }})
        .then(res=>res.json())
        .then((result)=>{
            if(result.code === "200" && Array.isArray(result.data)){
                result.data.forEach((item)=>{
                    item.id = item.userId;
                    item.name = item.userName;
                })
                setSearchList(result.data);
            }
        });
    }
    //选择用户
    const selectMethod = (data, e, type, addKind) => {
        e && e.stopPropagation();
        let list = JSON.parse(JSON.stringify(selectList));
        if(type === "list"){
            let arr = [];
            data.forEach((item)=>{
                let sign = false;
                let dataId = (item.groupType? item.groupType + "_": "") + item.id
                list.forEach((child, index)=>{
                    let childId = (child.groupType? child.groupType + "_": "") + child.id
                    if(childId === dataId){
                        sign = index;
                    }
                })
                if(typeof sign === "number"){
                    if(addKind === "add"){
                        return;
                    }
                    list.splice(sign, 1);
                } else {
                    list.push(item);
                }
            })
            setSelectList(list);
            return;
        }
        let dataId = (data.groupType? data.groupType + "_": "") + data.id;
        if(data.type === "user"){
            dataId = data.id;
        }
        let sign = false;
        list.forEach((item, index)=>{
            let allId = (item.groupType? item.groupType + "_": "") + item.id;
            if(data.type === "user"){
                allId = item.id;
            }
            if(allId === dataId){
                sign = index;
            }
        })
        if(type === "add" && sign){
            message.warn("该用户已被选择");
            return;
        }
        if(type === "add"){
            data.type = "user";
            setKeyword("");
        }
        if(typeof sign === "number"){
            list.splice(sign, 1);
        } else {
            list.push(data);
        }
        setSelectList(list);
    }
    //凸显搜索文字
    const highlightKey = (str) => {
        let arr = str.toString().split(keyword);
        let updateArr = [];
        arr.forEach((item, index)=>{
            if(index === arr.length - 1){
                updateArr.push(item);
            } else {
                updateArr.push(item);
                updateArr.push(
                    <span style={{color: "#ff6600"}}>{keyword}</span>
                )
            }
        })
        return updateArr;
    }
    //删除指定用户
    const deleteSelect = (index, type) => {
        if(type === "clear"){
            setSelectList([]);
            return;
        }
        let list = JSON.parse(JSON.stringify(selectList));
        list.splice(index, 1);
        setSelectList(list);
    }
    const confirmMethod = () => {
        //格式化返回对象，便于直接传参
        let obj = {
            teachers: [],
            students: [],
            departments: [],
            identities: [],
            parents: [],
            persons: [],
            allList: []
        };
        console.log(selectList);
        selectList.forEach((item)=>{
            if(item.type === "user"){
                obj.persons.push(item);
                return;
            }
            if(item.groupType === "stu"){
                let groupOne = {};
                switch (item.type){
                    case "class": 
                        groupOne = {
                            classId: item.id,
                            className: item.name
                        }
                        break;
                    case "grade": 
                        groupOne = {
                            gradeId: item.id,
                            gradeName: item.name
                        }
                        break;
                    default: 
                        break;
                }
                obj.students.push(groupOne);
                return;
            }
            if(item.groupType === "parent"){
                let groupOne = {};
                switch (item.type){
                    case "class": 
                        groupOne = {
                            classId: item.id,
                            className: item.name
                        }
                        break;
                    case "grade": 
                        groupOne = {
                            gradeId: item.id,
                            gradeName: item.name
                        }
                        break;
                    default: 
                        break;
                }
                obj.parents.push(groupOne);
                return;
            }
            if(item.groupType === "tea"){
                let groupOne = {};
                if(sessionStorage.getItem("schoolType") == 1){
                    groupOne = {
                        subjectId: item.id,
                        subjectName: item.name
                    }
                } else {
                    groupOne = {
                        groupId: item.id,
                        groupName: item.name
                    }
                }
                obj.teachers.push(groupOne);
                return;
            }
            if(item.groupType === "admin"){
                obj.identities.push({
                    identityCode: item.id,
                    identityName: item.name
                });
                return;
            }
            if(item.groupType === "org"){
                obj.departments.push({
                    departmentId: item.id,
                    departmentName: item.name
                });
                return;
            }
        })
        obj.allList = selectList;
        typeof getList === "function" &&
        getList(obj);
        cancelMethod();
    }
    const cancelMethod = () => {
        typeof changeVisible === "function" &&
        changeVisible(false);
        setSelectList([]);
        setSearchList([]);
        setKeyword("");
        setSearchVisible(false);
    }
    useLayoutEffect(()=>{
        searchUserMethod();
    }, [keyword]);
    useLayoutEffect(()=>{
        if(!visible){
            return;
        }
        if(Array.isArray(originList)){  //传入数组统一格式
            let list = JSON.parse(JSON.stringify(originList));
            list.forEach((item)=>{

                item.id = item.id || item.userId || item.identityCode || item.classId || item.subjectId || item.groupId || item.gradeId;
                item.name = item.name || item.userName || item.identityName || item.className || item.subjectName || item.groupName || item.gradeName;
            })
            setSelectList(list);
        }
    }, [visible]);
    return (
        <Modal
        width={width} 
        height={height}
        className="collect_select_modal"
        title={title? title: "选择发布对象"}
        visible={visible}
        noFooter={true}
        changeVisible={changeVisible}>
            <div className="collect_select_container">
                <div className="collect_select_left">
                    <Scrollbars autoHeight autoHeightMax={525}>
                    <div className="select_user_list">
                        {
                            selectList.map((item, index)=>{
                                return (
                                    <div className="user_one" key={index} title={
                                        item.name + (item.userId? "(" + item.userId + ")": "")
                                    }>
                                        {item.name}
                                        {
                                            item.userId?
                                            <span style={{
                                                color: "#999"
                                            }}>({item.userId})</span>:
                                            item.groupType?
                                            <span style={{
                                                color: "#999"
                                            }}>({groupTypeInfo[item.groupType]})</span>:
                                            ""
                                        }
                                        <i className="closelogo" onClick={()=>deleteSelect(index)}></i>
                                    </div>
                                )
                            })
                        }
                        <Popover
                        placement="bottom"
                        overlayClassName="collect_search_container"
                        visible={searchVisible}
                        // getPopupContainer={(trigger)=>trigger.parentElement}
                        destroyTooltipOnHide={true}
                        content={
                            <ul className="search_list">
                                <Scrollbars autoHeight autoHeightMax={240} autoHide>
                                {
                                    searchList.length > 0?
                                    searchList.map((item, index)=>{
                                        return (
                                            <li 
                                            key={index} 
                                            onClick={(e)=>selectMethod(item, e, "add")}
                                            title={item.userName + "(" + item.userId + ")"}>
                                                <i className="user_head" style={{
                                                    backgroundImage: `url('${item.avatarPath}')`
                                                }}></i>
                                                {highlightKey(item.userName)}
                                                <span style={{color: "#999"}}>({item.userId})</span>
                                            </li>
                                        )
                                    }):
                                    <p style={{
                                        height: 100,
                                        lineHeight: "100px",
                                        textAlign: "center",
                                        color: "#999"
                                    }}>暂无搜索结果</p>
                                }
                                </Scrollbars>
                            </ul>
                        }
                        >
                        <input 
                        type="text" 
                        className="search_user_input" 
                        placeholder="搜索..." 
                        // maxLength={12}
                        value={keyword}
                        autoComplete="off"
                        onFocus={()=>setSearchVisible(true)}
                        onBlur={()=>{
                            setTimeout(() => {
                                setSearchVisible(false);
                            }, 150);
                        }}
                        onChange={(e)=>setKeyword(e.target.value)} 
                        />
                        </Popover>
                        
                    </div>
                    </Scrollbars>
                    <div className="select_btn_group">
                        <div className="confirm_btn" onClick={confirmMethod}>确定</div>
                        <div className="cancel_btn" onClick={cancelMethod}>取消</div>
                    </div>
                </div>
                <div className="collect_select_right">
                    <Scrollbars autoHeight autoHide autoHeightMax={580}>
                    {
                        groupList.map((item, index)=>{
                            return (
                                <GroupOne 
                                groupData={item} 
                                selectMethod={selectMethod} 
                                selectList={selectList} 
                                key={index} />
                            )
                        })
                    }
                    </Scrollbars>
                </div>
            </div>
        </Modal>
    )
}

export default SelectModal;